var DIR={
	DIR_RIGHT:1,
	DIR_LEFT:2,
	DIR_TOP:3,
	DIR_BOTTOM:4,
};
var dir=DIR.DIR_RIGHT;
var snake=[];
var food=null;
window.onload=function(){
	//初始化地图
	initMap();
	//初始化蛇
	initSnake();
	//让蛇动起来
	setInterval(snakeMove,250);
	//显示食物
	showFood();
	
	document.onkeyup = function(e){
		switch(e.keyCode){
			case 37:dir=DIR.DIR_LEFT;break;
			case 38:dir=DIR.DIR_TOP; break;
			case 39:dir=DIR.DIR_RIGHT; break;
			case 40:dir=DIR.DIR_BOTTOM; break;
			default:break;
		}
	}
}
function initMap(){
	var con=document.getElementById("container");
	var num=parseInt((con.offsetHeight/50)*(con.offsetWidth/50));
	for(var i=0;i<num;i++){
		var newSpan=document.createElement("span");
		newSpan.className="map";
		con.appendChild(newSpan);
	}
}
function initSnake(){
	var con=document.getElementById("container");
	for(var i=1;i<=5;i++){
		var newBody=document.createElement('span');
		newBody.className="snake";
		newBody.style.top='0px';
		newBody.style.left=50*(i-1)+"px";
		con.appendChild(newBody);
		snake.push(newBody);
	}
}
function snakeMove(){
	var head=snake[snake.length-1];
	var newLeft=head.offsetLeft; 
	var newTop=head.offsetTop;
	switch(dir){
		case DIR.DIR_LEFT:
				newLeft-=50;
				break;
		case DIR.DIR_RIGHT:
				newLeft+=50;
				break;
		case DIR.DIR_TOP:
				newTop-=50;
				break;
		case DIR.DIR_BOTTOM:
				newTop+=50;
				break;
		default:
			break;
	}
	if(newLeft>=500) newLeft=0;
	if(newLeft<0) newLeft=450;
	if(newTop>=500) newTop=0;
	if(newTop<0) newTop=450;
	//蛇头进入身体
	for(var i=0;i<snake.length-1;i++){
		if(snake[i].offsetLeft==newLeft && snake[i].offsetTop==newTop){
			alert("Game Over!");
			window.location.href=window.location.href
		}
	}
	if(food.offsetLeft==newLeft && food.offsetTop==newTop){
		food.className="snake";
		snake.push(food);
		
		showFood();
		return;
	}	
	for(var i=0;i<snake.length-1;i++){
		snake[i].style.left=snake[i+1].offsetLeft+'px';
		snake[i].style.top=snake[i+1].offsetTop+'px';
	}
	head.style.left=newLeft+"px";
	head.style.top=newTop+"px";
}
function showFood(){
	food =document.createElement("span");
	food.className = "food";
	var left,top;
	do{
		left=Math.floor(Math.random()*10)*50;
		top=Math.floor(Math.random()*10)*50;
	}while(isInSnake(left,top))
	
	food.style.left=left+'px';
	food.style.top=top+'px';
	
	document.getElementById("container").appendChild(food);
}
function isInSnake(left,top){
	for(var i=0;i<snake.length;i++){
		if(snake[i].offsetLeft==left&&snake[i].offsetTop==top){
			return true;
		}
	}
	return false;
}
